import numpy as np
import librosa
from utils.logger import setup_logger

logger = setup_logger("audio_utils")


def normalize_audio(audio_data):
    """归一化音频数据"""
    max_val = np.max(np.abs(audio_data))
    if max_val > 0:
        return audio_data / max_val
    return audio_data


def extract_audio_features(audio_data, sample_rate=22050):
    """提取音频特征"""
    try:
        # 计算MFCC特征
        mfcc = librosa.feature.mfcc(y=audio_data, sr=sample_rate, n_mfcc=13)

        # 计算能量
        energy = np.sum(np.square(audio_data))

        # 计算过零率
        zero_crossing_rate = librosa.feature.zero_crossing_rate(audio_data)[0, 0]

        return {
            "mfcc": mfcc,
            "energy": energy,
            "zero_crossing_rate": zero_crossing_rate
        }
    except Exception as e:
        logger.error(f"音频特征提取失败: {e}")
        return None